const {port,host} = require("./config/config")
const Koa = require("koa");
const app = new Koa();
const path = require("path")
const fs = require("fs")

//连接数据库
require("./db/db")

//参数校验
const parameter = require('koa-parameter');
parameter(app);

//错误处理
const _ = require("lodash")
const error = require('koa-json-error')
const options = {
    postFormat: (e, obj) => {
        return  process.env.NODE_ENV === 'pro' ? _.omit(obj, 'stack') : obj
    }
}
app.use(error(options))

//将public目录作为一个静态资源目录
const serve = require('koa-static');
app.use(serve(__dirname + '/dist'));

//支持body的读取  支持json  支持urlencoded数据(input标签传递的数据都是urlencoded类型)
/*const bodyParser = require('koa-bodyparser');
app.use(bodyParser());*/
const koaBody = require('koa-body');
app.use(koaBody({
    multipart:true, //让koaBody支持更多的body类型
    formidable: {
        // 上传目录
        uploadDir: path.join(__dirname, './public/img'),
        // 保留文件扩展名
        keepExtensions: true,
    }
}));

//路由器注册 (批量注册路由器)
const Router = require('@koa/router');
const requireDirectory = require('require-directory');
requireDirectory(module, "./router" ,{visit: (obj)=>{
    //obj :  userRouter ,orderRouter , {c:"c"}
    // 只要obj是一个路由器对象 我们就要进行路由器的注册
    if(obj instanceof Router){
        app.use(obj.routes()).use(obj.allowedMethods())
    }
}});

//配404
app.use((ctx)=>{
    console.log(typeof ctx.status);
    if(ctx.status === 404){
        //返回dist中的index.html
        const indexstream = fs.createReadStream(__dirname+"/dist/index.html")
        // ctx.set("Content-Type","text/html")
        ctx.type = "text/html";
        ctx.body = indexstream;
    }
})

app.listen(port,host,()=>{
    console.log(`server is running on http://${host}:${port}`)
})